package com.oauth.config;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.oauth2.client.CommonOAuth2Provider;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Configuration
public class ProjectConfig{
	@Bean
	SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
		httpSecurity.authorizeHttpRequests(auto->{
			auto.requestMatchers("/").permitAll();
		});
		httpSecurity.oauth2Login(login->{
			login.successHandler(new AuthenticationSuccessHandler() {
				@Override
				public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
					response.sendRedirect("/main");
				}
			});
		});
		httpSecurity.authorizeHttpRequests(auto->{
			auto.anyRequest().authenticated();
		});
		return httpSecurity.build();
	}
	/*ClientRegistration clientRegistration(){
		return ClientRegistration.withRegistrationId("GitHub")
				.clientId("f43e51af3fc2d5943bc3")
				.clientSecret("778188d6db6d11a17fcdc54869cb5a5491d5df50")
				.scope(new String[]{"read:user"})
				.authorizationUri("https://github.com/login/oauth/authorize")
				.userInfoUri("https://api.github.com/user")
				.userNameAttributeName("id")
				.clientName("Github")
				.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
				.redirectUri("{b    aseUrl}/{action}/oauth2/code/{registrationId}")
				.build();
	}*/
	private ClientRegistration clientRegistration() {
		return CommonOAuth2Provider.GITHUB.getBuilder("github")
				.clientId("f43e51af3fc2d5943bc3")
				.clientSecret("778188d6db6d11a17fcdc54869cb5a5491d5df50")
				.build();
	}

	//将ClientRegistrationRepository类型的bean添加到Spring上下文，该bean包含对ClientRegistration的引用
	@Bean
	public ClientRegistrationRepository clientRepository() {
		var c = clientRegistration();
		return new InMemoryClientRegistrationRepository(c);
	}
}
